﻿//==================================================================
// Copyright (C) 2011 深圳市中旭企业管理股份有限公司
// 文件名: SysCustomDefineForm.cs
// 作 者：代码自动生成
// 日 期：2012-2-16 10:45:09
// 描 述：
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
// 1.00             
//==================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Text;
using System.Data;
using Csla;
using lite;
using Csla.Validation;
using Csla.Data;
using System.Data.SqlClient;
using ZX.DAL;
using Csla.Core;
using OpenExpressApp.ORM;
using OpenExpressApp.MetaAttribute;
using OpenExpressApp.DB.Utils;
using OpenExpressApp;


namespace ZX.SYS.Library
{
	/// <summary>
    /// 
    /// </summary>
	[Serializable]
    [Table(Name="SysCustomDefineForm")]
    [ZX.DBModule.Table("SysCustomDefineForm","FormID")]
    public partial class SysCustomDefineForm : GBusinessBase<SysCustomDefineForm>
	{
        #region Business Methods 业务方法
       
		/// <summary>
        /// 表单ID
        /// </summary>
        private static PropertyInfo< Guid > FormIDProperty = RegisterProperty(typeof(SysCustomDefineForm),new PropertyInfo< Guid >("FormID"));
        [DataObjectField(true, true)]
        [Column, PK]
        public Guid FormID
        {
            get { return GetProperty(FormIDProperty); }
            set { SetProperty(FormIDProperty, value); }
        }
        
		/// <summary>
        /// 表单名称
        /// </summary>
        private static PropertyInfo< string > FormNameProperty = RegisterProperty(typeof(SysCustomDefineForm),new PropertyInfo< string >("FormName"));
        [Column]
        public string FormName
        {
            get { return GetProperty(FormNameProperty); }
            set { SetProperty(FormNameProperty, value); }
        }
		/// <summary>
        /// 主表名称
        /// </summary>
        private static PropertyInfo< string > MasterTableNameProperty = RegisterProperty(typeof(SysCustomDefineForm),new PropertyInfo< string >("MasterTableName"));
        [Column]
        public string MasterTableName
        {
            get { return GetProperty(MasterTableNameProperty); }
            set { SetProperty(MasterTableNameProperty, value); }
        }
		/// <summary>
        /// 模板名称
        /// </summary>
        private static PropertyInfo< string > TemplateNameProperty = RegisterProperty(typeof(SysCustomDefineForm),new PropertyInfo< string >("TemplateName"));
        [Column]
        public string TemplateName
        {
            get { return GetProperty(TemplateNameProperty); }
            set { SetProperty(TemplateNameProperty, value); }
        }
		/// <summary>
        /// 主表设置信息
        /// </summary>
        private static PropertyInfo< string > MasterJsonProperty = RegisterProperty(typeof(SysCustomDefineForm),new PropertyInfo< string >("MasterJson"));
        [Column]
        public string MasterJson
        {
            get { return GetProperty(MasterJsonProperty); }
            set { SetProperty(MasterJsonProperty, value); }
        }
		/// <summary>
        /// 明细设置信息
        /// </summary>
        private static PropertyInfo< string > DetailsJsonProperty = RegisterProperty(typeof(SysCustomDefineForm),new PropertyInfo< string >("DetailsJson"));
        [Column]
        public string DetailsJson
        {
            get { return GetProperty(DetailsJsonProperty); }
            set { SetProperty(DetailsJsonProperty, value); }
        }
		/// <summary>
        /// html字符串
        /// </summary>
        private static PropertyInfo< string > HtmlStringProperty = RegisterProperty(typeof(SysCustomDefineForm),new PropertyInfo< string >("HtmlString"));
        [Column]
        public string HtmlString
        {
            get { return GetProperty(HtmlStringProperty); }
            set { SetProperty(HtmlStringProperty, value); }
        }
		/// <summary>
        /// 状态(签入:in、签出:out、失效:failure)
        /// </summary>
        private static PropertyInfo< string > StateProperty = RegisterProperty(typeof(SysCustomDefineForm),new PropertyInfo< string >("State"));
        [Column]
        public string State
        {
            get { return GetProperty(StateProperty); }
            set { SetProperty(StateProperty, value); }
        }
		/// <summary>
        /// 版本
        /// </summary>
        private static PropertyInfo< int > VersionProperty = RegisterProperty(typeof(SysCustomDefineForm),new PropertyInfo< int >("Version"));
        [Column]
        public int Version
        {
            get { return GetProperty(VersionProperty); }
            set { SetProperty(VersionProperty, value); }
        }
		/// <summary>
        /// 次版本
        /// </summary>
        private static PropertyInfo< int > PatchProperty = RegisterProperty(typeof(SysCustomDefineForm),new PropertyInfo< int >("Patch"));
        [Column]
        public int Patch
        {
            get { return GetProperty(PatchProperty); }
            set { SetProperty(PatchProperty, value); }
        }
		/// <summary>
        /// 创建人
        /// </summary>
        private static PropertyInfo< Guid > AddUserProperty = RegisterProperty(typeof(SysCustomDefineForm),new PropertyInfo< Guid >("AddUser"));
        [Column]
        public Guid AddUser
        {
            get { return GetProperty(AddUserProperty); }
            set { SetProperty(AddUserProperty, value); }
        }
		/// <summary>
        /// 创建日
        /// </summary>
        private static PropertyInfo< DateTime > AddtimeProperty = RegisterProperty(typeof(SysCustomDefineForm),new PropertyInfo< DateTime >("Addtime"));
        [Column]
        public DateTime Addtime
        {
            get { return GetProperty(AddtimeProperty); }
            set { SetProperty(AddtimeProperty, value); }
        }

        private static PropertyInfo<SysFieldItems> FieldItemsProperty = RegisterProperty(new PropertyInfo<SysFieldItems>("SysFieldItems"));

        public SysFieldItems FieldItems
        {
            get
            {
                if (!FieldManager.FieldExists(FieldItemsProperty))
                {
                    LoadProperty(FieldItemsProperty, SysFieldItems.NewChild());
                }
                return GetProperty(FieldItemsProperty);
            }
        }

        public override BusinessBase MergeOldObject(BusinessBase oldObject)
        {
            if (null == oldObject) return null;

            SysCustomDefineForm _detailItem = oldObject as SysCustomDefineForm;
            LoadProperty(FormIDProperty, _detailItem.FormID);
            LoadProperty(FormNameProperty, _detailItem.FormName);
            LoadProperty(MasterTableNameProperty, _detailItem.MasterTableName);
            LoadProperty(TemplateNameProperty, _detailItem.TemplateName);
            LoadProperty(MasterJsonProperty, _detailItem.MasterJson);
            LoadProperty(DetailsJsonProperty, _detailItem.DetailsJson);
            LoadProperty(HtmlStringProperty, _detailItem.HtmlString);
            LoadProperty(StateProperty, _detailItem.State);
            LoadProperty(VersionProperty, _detailItem.Version);
            LoadProperty(PatchProperty, _detailItem.Patch);
            LoadProperty(AddUserProperty, _detailItem.AddUser);
            LoadProperty(AddtimeProperty, _detailItem.Addtime);

            var orderItems = SysFieldItems.NewChild();
            orderItems.AddRange((oldObject as SysCustomDefineForm).FieldItems);
            LoadProperty(FieldItemsProperty, orderItems);

            return base.MergeOldObject(oldObject);
        }
        #endregion
        
        #region Validation Rules 验证规则
        //将验证规则与业务对象的属性联系在一起
        protected override void AddBusinessRules()
        {
            //AddRule的第一个参数是委托变量，也就是说是方法的变量
            //ValidationRules.AddRule(CommonRules.StringRequired, "FormName");
            //ValidationRules.AddRule(CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("FormName", 50));
            //ValidationRules.AddRule(CommonRules.StringRequired, "MasterTableName");
            //ValidationRules.AddRule(CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("MasterTableName", 30));
            //ValidationRules.AddRule(CommonRules.StringRequired, "TemplateName");
            //ValidationRules.AddRule(CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("TemplateName", 30));
            //ValidationRules.AddRule(CommonRules.StringRequired, "MasterJson");
            //ValidationRules.AddRule(CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("MasterJson", 16));
            //ValidationRules.AddRule(CommonRules.StringRequired, "DetailsJson");
            //ValidationRules.AddRule(CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("DetailsJson", 16));
            //ValidationRules.AddRule(CommonRules.StringRequired, "HtmlString");
            //ValidationRules.AddRule(CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("HtmlString", 16));
            //ValidationRules.AddRule(CommonRules.StringRequired, "State");
            //ValidationRules.AddRule(CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("State", 7));
            //base.AddBusinessRules();
        }
        #endregion
        
        #region Factory Methods 工厂方法

        public SysCustomDefineForm()
        {
            IsObjectLazy = true; 
        }

        public static SysCustomDefineForm New()
        {
            return DataPortal.Create< SysCustomDefineForm>();
        }
        public static SysCustomDefineForm Get(Guid formID)
        {
            return DataPortal.Fetch<SysCustomDefineForm>(new SingleLazyCriteria<SysCustomDefineForm, Guid>(formID, false));
        }

        internal static SysCustomDefineForm GetLazy(Guid formID)
        {
            return DataPortal.Fetch<SysCustomDefineForm>(new SingleLazyCriteria<SysCustomDefineForm, Guid>(formID, true));
        }

        public static void Delete(Guid formID)
        {
            DataPortal.Delete(new SingleCriteria<SysCustomDefineForm, Guid>(formID));
        }

        #endregion
		
		#region Data Access 数据访问
        //由于DataPortal_create中没有对数据库的访问，所有标记了Runlocal特性，使得该方法只需在本地运行即可
        //如果代码中有访问数据库的方法，那么就不要用这个特性，使数据门户可以根据情况将此方法的运行选择在应用服务器还是本地
        [RunLocal()]
        protected override void DataPortal_Create()
        {
            //在此调用CheckRules对所有的属性进行验证规则的检查，这样检查只运行一次。
            LoadProperty(FormIDProperty,Guid.NewGuid());
            ValidationRules.CheckRules();
        }


        //可以看到此方法没有标记任何特性
        //此方法要访问数据库所以不能标记本地，由于她没有任何数据库更新操作所以也无需事务性的保护
        //此方法调用结束后会隐含的调用MarkOld（）方法
        private void DataPortal_Fetch(SingleLazyCriteria<SysCustomDefineForm, Guid> criteria)
        {
            //通过连接字符串建立SQL连接对象，Using符号代表，范围释放的意思，SqlConnection对象会在此范围后被释放掉
            using (var ctx = ConnectionManager<SqlConnection>.GetManager(ZX.DBModule.BaseEntity.ConnectionStringNames))
            {
                IDb db = DbFactory.Instance.GetDb(ctx.Connection);
                IQuery q = db.Query();
                q.Constrain("FormID").Equal(criteria.Value);
                var data = db.Select< SysCustomDefineForm>(q)[0];
                LoadProperty(FormIDProperty, data.FormID);
                LoadProperty(FormNameProperty, data.FormName);
                LoadProperty(MasterTableNameProperty, data.MasterTableName);
                LoadProperty(TemplateNameProperty, data.TemplateName);
                LoadProperty(MasterJsonProperty, data.MasterJson);
                LoadProperty(DetailsJsonProperty, data.DetailsJson);
                LoadProperty(HtmlStringProperty, data.HtmlString);
                LoadProperty(StateProperty, data.State);
                LoadProperty(VersionProperty, data.Version);
                LoadProperty(PatchProperty, data.Patch);
                LoadProperty(AddUserProperty, data.AddUser);
                LoadProperty(AddtimeProperty, data.Addtime);

                this.IsObjectLazy = criteria.IsObjectLazy;
                if (!IsObjectLazy)
                {
                    LoadProperty(FieldItemsProperty, SysFieldItems.GetChild(this));
                }
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_Insert()
        {
            using (var ctx = ConnectionManager<SqlConnection>.GetManager(ZX.DBModule.BaseEntity.ConnectionStringNames))
            {
                IDb db = DbFactory.Instance.GetDb(ctx.Connection);
                db.Insert(this);
                // update child objects
                FieldManager.UpdateChildren(this);
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_Update()
        {
            using (var ctx = ConnectionManager<SqlConnection>.GetManager(ZX.DBModule.BaseEntity.ConnectionStringNames))
            {
                IDb db = DbFactory.Instance.GetDb(ctx.Connection);
                db.Update(this);
                // update child objects
                FieldManager.UpdateChildren(this);
            }
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(this.FormID);
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        private void DataPortal_Delete(Guid formid)
        {
            using (var ctx = ConnectionManager<SqlConnection>.GetManager(ZX.DBModule.BaseEntity.ConnectionStringNames))
            {
                IDb db = DbFactory.Instance.GetDb(ctx.Connection);
                db.Delete(typeof(SysCustomDefineForm), db.Query().Constrain("FormID").Equal(formid));
            }

        }

        public IGTable getTableInfo()
        {
            IGTable dt = null;
            using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
            {
                string sql = " select TableName as DisplayMember ,Notes, CONVERT(varchar(36), TableID)+'@'+TableName as ValueMember from Set_Table   where SUBSTRING(TableName,0,4) not in('Dat','Sys','Set','HF_') ";
               dt = db.QueryTable(sql);
            }
            return dt;
        }
        /// <summary>
        /// 判断是否有指定表单名
        /// </summary>
        /// <param name="formName"></param>
        /// <returns></returns>
        public bool getIExistFormName(string formName)
        {
            bool isExist=false;
            using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
            {
                string sql = "select FormName from SysCustomDefineForm where FormName='" + formName + "'";
                IGTable dt = db.QueryTable(sql); 
                if (dt.Count > 0) 
                {
                isExist=true;
                }else{isExist=false;}
            }
            return isExist;
        }
        public IGTable getTableField(string TableName) 
        {
            IGTable dt = null;
            using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
            {
                StringBuilder sbsql = new StringBuilder();
                sbsql.Append("select * from( ");
                sbsql.Append("SELECT TOP 100 PERCENT ");
                sbsql.Append("cast( d.name as varchar)  AS EntityName, ");
                sbsql.Append("cast(a.colorder as int) AS ColSeq, ");
                sbsql.Append("cast(a.name as nvarchar) AS ColName,");

               sbsql.Append("cast(CASE WHEN b.name ='uniqueidentifier' then 'string' ");
               sbsql.Append("WHEN b.name ='nvarchar' then 'string' ");
               sbsql.Append("WHEN b.name ='char' then 'string' ");
               sbsql.Append("WHEN b.name ='image' then 'string' ");
               sbsql.Append("WHEN b.name ='varchar' then 'string' ");
               sbsql.Append("WHEN b.name ='text' then 'string' ");
               sbsql.Append("WHEN b.name ='int' then 'int' ");
               sbsql.Append("WHEN b.name ='decimal' then 'decimal' ");
               sbsql.Append("WHEN b.name ='bit' then 'int' ");
               sbsql.Append("WHEN b.name ='numeric' then 'decimal' ");
               sbsql.Append("WHEN b.name ='tinyint' then 'int' ");
               sbsql.Append("WHEN b.name ='datetime' then 'datetime' ");
               sbsql.Append("end as nvarchar) AS CType, ");

               sbsql.Append(" cast(CASE WHEN a.isnullable = 1 THEN 'empty' ELSE 'required' END as char) AS CanNull,  ");
                sbsql.Append("cast(ISNULL(g.[value], '') as nvarchar)AS ColDesc,'textfield' as ControlsType,'false' as iSun_Selected  ");
                sbsql.Append("FROM dbo.syscolumns a LEFT OUTER JOIN ");
                sbsql.Append(" dbo.systypes b ON a.xtype = b.xusertype INNER JOIN ");
                sbsql.Append("dbo.sysobjects d ON a.id = d.id AND d.xtype = 'U' AND ");
                sbsql.Append("d.status >= 0 LEFT OUTER JOIN ");
                sbsql.Append("sys.extended_properties g ON a.id = g.major_id AND a.colid = g.minor_id AND ");
                sbsql.Append("g.name = 'MS_Description' ");
                sbsql.Append(") a where EntityName='" + TableName + "' ORDER BY  ColSeq");

                dt = db.QueryTable(sbsql.ToString());
            }
            return dt;
        }

       
        #endregion
        #region 分司、部门、团队、岗位
        /// <summary>
        /// 获取所有分公司
        /// </summary>
        /// <returns></returns>
        public List<ZX.DBModule.Dictionary> GetOrganizeAll()
        {
            List<ZX.DBModule.Dictionary> list = new List<ZX.DBModule.Dictionary>();
            try
            {
                using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
                {
                    IResultSet rs = db.Exec("sp_GetOrganizeAll", new object[] { });
                    if (rs.Rows > 0)
                    {
                        for (int i = 0; i < rs.Rows; i++)
			            {
                            ZX.DBModule.Dictionary dic = new ZX.DBModule.Dictionary();
                            dic.DisplayMember=rs.Get(i,"Name").ToString();
                            dic.ValueMember=rs.Get(i,"Value").ToString();
                            list.Add(dic);
			            }
                    }
                }
            }
            catch (Exception ex){throw ex;}
            return list;
        }
        // /// <summary>
        ///// 获取指定分公司的所有部门
        // /// </summary>
        // /// <param name="DeptID">部门ID</param>
        // /// <returns></returns>
        //public List<ZX.DBModule.Dictionary> GetcompanyByDepartment(Guid DeptID)
        //{
        //    List<ZX.DBModule.Dictionary> list = new List<ZX.DBModule.Dictionary>();
        //    try
        //    {
        //        using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
        //        {
        //            IResultSet rs = db.Exec("sp_GetcompanyByDepartment", new object[] { DeptID });
        //            if (rs.Rows > 0)
        //            {
        //                for (int i = 0; i < rs.Rows; i++)
        //                {
        //                    ZX.DBModule.Dictionary dic = new ZX.DBModule.Dictionary();
        //                    dic.DisplayMember = rs.Get(i, "Name").ToString();
        //                    dic.ValueMember = rs.Get(i, "Value").ToString();
        //                    list.Add(dic);
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex) { throw ex; }
        //    return list;
        //}

        ///// <summary>
        ///// 获取指定部门的所有团队
        ///// </summary>
        ///// <param name="DeptID"></param>
        ///// <returns></returns>
        //public List<ZX.DBModule.Dictionary> GetDepartmentByTeam(Guid DeptID)
        //{
        //    List<ZX.DBModule.Dictionary> list = new List<ZX.DBModule.Dictionary>();
        //    try
        //    {
        //        using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
        //        {
        //            IResultSet rs = db.Exec("sp_GetDepartmentByTeam", new object[] { DeptID });
        //            if (rs.Rows > 0)
        //            {
        //                for (int i = 0; i < rs.Rows; i++)
        //                {
        //                    ZX.DBModule.Dictionary dic = new ZX.DBModule.Dictionary();
        //                    dic.DisplayMember = rs.Get(i, "Name").ToString();
        //                    dic.ValueMember = rs.Get(i, "Value").ToString();
        //                    list.Add(dic);
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex) { throw ex; }
        //    return list;
        //}
        /// <summary>
        /// 获取指定部门的所有岗位
        /// </summary>
        /// <param name="DeptID"></param>
        /// <returns></returns>
        public List<ZX.DBModule.Dictionary> GetDepartmentByPost(Guid DeptID)
        {
            List<ZX.DBModule.Dictionary> list = new List<ZX.DBModule.Dictionary>();
            try
            {
                using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
                {
                    IResultSet rs = db.Exec("sp_GetDepartmentByPost", new object[] { DeptID });
                    if (rs.Rows > 0)
                    {
                        for (int i = 0; i < rs.Rows; i++)
                        {
                            ZX.DBModule.Dictionary dic = new ZX.DBModule.Dictionary();
                            dic.DisplayMember = rs.Get(i, "Name").ToString();
                            dic.ValueMember = rs.Get(i, "Value").ToString();
                            list.Add(dic);
                        }
                    }
                }
            }
            catch (Exception ex) { throw ex; }
            return list;
        }
        #endregion
        public override string ToString()
        {
            return FormName;
        }
	}

    /// <summary>
    ///  明细表数据源设置类
    /// </summary>
    public  class SysDetailsItem
    {
       /// <summary>
       /// 主键ID
       /// </summary>
       public string ID{get;set;}
       /// <summary>
       /// 明细表名
       /// </summary>
       public string DetailsTableName{get;set;}
       /// <summary>
       /// 主键字符串[可以多个主键用‘,‘,分开]
       /// </summary>
       public string PrimaryKey{get;set;}
    };

}

